package com.tybbank.Login;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tybbank.Activity.MainActivity;
import com.tybbank.Activity.YUYANActivity;
import com.tybbank.Base.BaseActivity;
import com.tybbank.Bean.LoginBean;
import com.tybbank.MyApplication;
import com.tybbank.R;
import com.tybbank.Utils.Constant;
import com.tybbank.Utils.LocalManageUtil;
import com.tybbank.Utils.MD5Utils;
import com.tybbank.Utils.MyDialogUtils;
import com.tybbank.Utils.StatusBarUtil;
import com.tybbank.Utils.logUtilssss;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.Comparator;
import java.util.Date;
import java.util.SortedMap;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.tybbank.Activity.MainActivity.TWO_SECOND;

/**
 * Created by Administrator on 2018/9/21 0021.
 */

public class LoginActivity extends BaseActivity {
    @BindView(R.id.et_account)
    EditText etAccount;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.tv_registervip)
    Button tvRegistervip;
    @BindView(R.id.tv_forgetPsw)
    TextView tvForgetPsw;
    @BindView(R.id.bt_enter_login)
    Button btEnterLogin;
    long preTime;
    @BindView(R.id.sp_spinner)
    TextView tv_yuyan;
    private String password;
    private String time;
    private Intent intent;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            StatusBarUtil.setStatusBarColor(LoginActivity.this, R.color.backgroundcolorhei723);
        }

        setValue();
    }
    @SuppressLint("StringFormatInvalid")
    private void setValue() {
        String string = getString(R.string.denglu,
                LocalManageUtil.getSystemLocale(this).getDisplayLanguage());
        btEnterLogin.setText(string);

    }

    @OnClick({R.id.tv_registervip, R.id.tv_forgetPsw, R.id.bt_enter_login, R.id.sp_spinner})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.sp_spinner:
                intent = new Intent(this, YUYANActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_registervip:
                intent = new Intent(this, RegisterVipActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_forgetPsw:
                intent = new Intent(this, FindPasswordActivity.class);
                startActivity(intent);
                break;
            case R.id.bt_enter_login:
                if (TextUtils.isEmpty(etAccount.getText().toString().trim())) {
                    logUtilssss.toast(this, getString(R.string.account));
                } else if (TextUtils.isEmpty(etPassword.getText().toString().trim())) {
                    logUtilssss.toast(this, getString(R.string.pwd));
                } else {
                    password = MD5Utils.md5Password(etPassword.getText().toString().trim());
                    time = MD5Utils.getTime();
                    SortedMap<String, String> parameters = new TreeMap<String, String>(
                            new Comparator<String>() {
                                public int compare(String obj1, String obj2) {
                                    // 降序排序
                                    return obj1.compareTo(obj2);
                                }
                            });
                    parameters.put("account", etAccount.getText().toString().trim());
                    parameters.put("login_pwd", password);
                    parameters.put("TimeStamp", time);
                    String sign = MD5Utils.createSign(parameters);
                    initdata(sign);


                }
                break;
        }
    }

    private void initdata(String sign) {
        final Dialog dialog = MyDialogUtils.createLoadingDialog(this, getString(R.string.loading));
        dialog.show();
        OkHttpUtils
                .post()
                .url(Constant.LOGIN)
                .addParams("account", etAccount.getText().toString().trim())
                .addParams("login_pwd", password)
                .addParams("TimeStamp", time)
                .addParams("Sign", sign)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                        dialog.dismiss();
                        logUtilssss.toasteero(LoginActivity.this);
                        return;
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        logUtilssss.e("TAG用户登录" + response.toString());
                        dialog.dismiss();
                        string(response);
                    }

                    private void string(String json) {
                        LoginBean enterBean = new Gson().fromJson(json, new TypeToken<LoginBean>() {
                        }.getType());
                        int status = enterBean.getCode();
                        if (status == 1001) {
                            LoginBean<LoginBean.DataBean> bean = new Gson().fromJson(json, new TypeToken<LoginBean<LoginBean.DataBean>>() {
                            }.getType());
                            String token = bean.getData().getToken();
                            String uuid = bean.getData().getUuid();
                            MyApplication.token = bean.getData().getToken();
                            MyApplication.uuid = bean.getData().getUuid();
                            String mobile = bean.getData().getAccount();
                            SaveData(token, uuid, mobile);
                            intent = new Intent(LoginActivity.this, MainActivity.class);
                            intent.setFlags(intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(intent);
                            LoginActivity.this.finish();
                        } else {
                            logUtilssss.toast(LoginActivity.this, enterBean.getMsg());
                        }
                    }
                });

    }

    private void SaveData(String token, String uuid, String mobile) {
        SharedPreferences share = getSharedPreferences("user", 0);
        SharedPreferences.Editor edit = share.edit();
        edit.putString("token", token);
        edit.putString("uuid", uuid);
        edit.putString("phone", mobile);
        edit.commit();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 截获后退键
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            long currentTime = new Date().getTime();

            // 如果时间间隔大于2秒, 不处理
            if ((currentTime - preTime) > TWO_SECOND) {
                // 显示消息
                Toast.makeText(this, getString(R.string.outapp),
                        Toast.LENGTH_SHORT).show();

                // 更新时间
                preTime = currentTime;

                // 截获事件,不再处理
                return true;
            }
            System.exit(0);
        }
        return super.onKeyDown(keyCode, event);
    }
    public static void reStart(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }
}
